package com.rr.study02.filter;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.rr.study02.util.EntityManagerUtil;

public class JpaFilter implements Filter{
	
	private EntityManagerFactory factory;

	@Override
	public void destroy() {
		System.out.println("Entrou aqui: JpaFilter.destroy");
        this.factory.close();  		
	}

	@Override
	public void doFilter(ServletRequest serRequest, ServletResponse serResponse,
			FilterChain filChain) throws IOException, ServletException {
		System.out.println("Entrou aqui: JpaFilter.doFilter");

		EntityManager entManager = this.factory.createEntityManager();
		EntityManagerUtil.ENTITY_MANAGER.set(entManager);
		entManager.getTransaction().begin();
        System.out.println("Abriu transation.");
		filChain.doFilter(serRequest, serResponse);  
		System.out.println("Saiu do doFilter.");
        try {  
            entManager.getTransaction().commit();  
            System.out.println("Fez commit.");
        } catch (Exception exception) {  
            entManager.getTransaction().rollback();  
            System.out.println("Fez rollback.");
        }finally{  
        	EntityManagerUtil.ENTITY_MANAGER.remove();
            entManager.close();  
            System.out.println("Fez close.");
        }
	}

	@Override
	public void init(FilterConfig filConfig) throws ServletException {
		System.out.println("Entrou aqui: jpaFilter.init");
		this.factory = Persistence.createEntityManagerFactory("Formacao-02");
	}

}
